package com.java.compilation.helper;

import com.java.compilation.JackTokenizer;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class XmlWriter {

    private PrintWriter printWriter;

    public XmlWriter(File xmlFile) {
        try {
            printWriter = new PrintWriter(xmlFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void print(String... lines) {
        for (String line : lines) {
            printWriter.print(line);
        }
        printWriter.flush();
    }

    public void println(String... lines) {
        for (String line : lines) {
            printWriter.println(line);
        }
        printWriter.flush();
    }
    
    public void println(JackTokenizer tokenizer) {
        if (tokenizer.tokenType() == TokenType.KEYWORD) {
            println("<keyword> " + tokenizer.keyword().name().toLowerCase() + " </keyword>");
        } else if (tokenizer.tokenType() == TokenType.SYMBOL) {
            println("<symbol> " + convertSymbol(tokenizer.symbol()) + " </symbol>");
        } else if (tokenizer.tokenType() == TokenType.STRING_CONST) {
            println("<stringConstant> " + tokenizer.stringVal() + " </stringConstant>");
        } else if (tokenizer.tokenType() == TokenType.INT_CONST) {
            println("<integerConstant> " + tokenizer.intVal() + " </integerConstant>");
        } else if (tokenizer.tokenType() == TokenType.IDENTIFIER) {
            println("<identifier> " + tokenizer.identifier() + " </identifier>");
        }
    }


    public static String convertSymbol(String symbol) {
        if (symbol.equals("<")) {
            symbol = "&lt;";
        } else if (symbol.equals(">")) {
            symbol = "&gt;";
        } else if (symbol.equals("&")) {
            symbol = "&amp;";
        }
        return symbol;
    }

    public void close() {
        printWriter.close();
    }
}
